package com.tongji.showroom.view
{
	import alternativa.engine3d.loaders.collada.collada;
	
	import com.adobe.images.PNGEncoder;
	import com.tongji.showroom.events.AddUserProductEvent;
	import com.tongji.showroom.events.DeleteObjEvent;
	import com.tongji.showroom.events.GetSystemSceneEvent;
	import com.tongji.showroom.events.GetTypesEvent;
	import com.tongji.showroom.events.GetUserSceneEvent;
	import com.tongji.showroom.model.PictureModel;
	import com.tongji.showroom.model.UserModel;
	import com.tongji.showroom.utils.Matting;
	import com.tongji.showroom.view.FirstStepUploadLeftComp;
	import com.tongji.showroom.vo.Picture;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.NetConnection;
	import flash.net.Responder;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.ByteArray;
	
	import mx.binding.utils.BindingUtils;
	import mx.collections.ArrayCollection;
	import mx.collections.ArrayList;
	import mx.controls.Alert;
	import mx.core.INavigatorContent;
	import mx.core.UIComponent;
	import mx.graphics.codec.PNGEncoder;
	import mx.utils.Base64Decoder;
	import mx.utils.Base64Encoder;
	
	import org.robotlegs.mvcs.Mediator;
	
	/**
	 * 这个类是从本地选取图片，同时在list中显示其简单信息并对其进行上传和删除
	 * @author chenzhongyuan
	 * 2011-7-18
	 */		
	
	public class FirstStepUploadLeftCompMediator extends Mediator
	{
		[Inject]
		public var view:FirstStepUploadLeftComp;
		
		[Inject]
		public var model:PictureModel;
		private var nc:NetConnection;
		private var picture:Picture;
		private var pictureLocateArray:Array = new Array("images/餐桌.png", "images/床.png", "images/沙发.png");
		private var file:FileReference = new FileReference();
		private var loader:Loader;
		private var readyArray:ArrayCollection = new ArrayCollection();//暂时存放所选择的图片
		private static var maxSize:Number = 2048 * 1024;
		private var imagesFilter:FileFilter = new FileFilter("图像文件(*.jpg,*.gif,*.png)", "*.jpg;*.gif;*.png");
		private var uploadURL:URLRequest = new URLRequest("http://design.rryjw.com/taobaoupload.aspx");
		
		private var imgList:Array;
		[Inject]
		public var userModel:UserModel;
		
		override public function onRegister():void
		{
			imgList = new Array();
			dispatch( new GetTypesEvent(GetTypesEvent.GET_PLACES)); 
			dispatch( new GetTypesEvent(GetTypesEvent.GET_STYLES));
			dispatch( new GetSystemSceneEvent(GetSystemSceneEvent.GET_ALL_SCENE, "", "", 1, 9, null));
			BindingUtils.bindProperty(view.pictureMessage, "dataProvider", model, "pictureArray");
			BindingUtils.bindProperty(view.waitingNum, "text", model, "pictureNum");

			addViewListener(DeleteObjEvent.FIRSTLEFT_DELETE_PIC, deletePicture);
			eventMap.mapListener(view.addImageBtn, MouseEvent.CLICK, addImageBtnClickHandler);
			eventMap.mapListener(view.clearListBtn, MouseEvent.CLICK, clearListBtnClickHandler);
		}
		
		private function addImageBtnClickHandler(event:MouseEvent):void
		{
			file = new FileReference();
			try
			{
				file.browse([imagesFilter]);	
			}
			catch(illegalOperation:IllegalOperationError)
			{
			}
			eventMap.mapListener(file, Event.SELECT, onSelectFile);
		}
		
		//选择欲上传的图片
		private function onSelectFile(event:Event):void
		{
			if (file.size > maxSize)
				Alert.show("您的照片容量已经超过2M了，请压缩后重新上传！");
			else
			{				
				file.load();
				readyArray.addItem(file);
				eventMap.mapListener(file, Event.COMPLETE, completeHandler);
				eventMap.unmapListener(file, Event.SELECT, onSelectFile);
			}					
		}
		
		private function completeHandler(event:Event):void
		{
			loader = new Loader();
			
			/*file.data;
			var bitmapdata:BitmapData = new BitmapData(loader.width, loader.height);
			bitmapdata.draw(loader);
			var bitmap:Bitmap = new Bitmap(bitmapdata);
			var matting:Matting = new Matting(bitmap);
			var newbitmapdata:BitmapData = matting.startMatting().bitmapData;*/
			//var temp:ByteArray = 
			//var newbitmapdata:BitmapData = new BitmapData();
			loader.loadBytes(file.data);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);	
			eventMap.unmapListener(file, Event.COMPLETE, completeHandler);

		}
		
		private function loaderCompleteHandler(event:Event):void
		{
			if (event.target.width > 1700 || event.target.height > 1500)
			{
				Alert.show("您的照片尺寸太大了，建议改为700*500，然后再重新上传！");
			}
			else
			{
				picture = new Picture();
				picture.pictureName = file.name;
				picture.pictureSize = (int) (file.size / 1024) + 'KB';
				picture.pictureId = model.pictureArray.length + 1;
				picture.pictureUpdate = false;
				picture.pictureSelected = false;
				picture.pictureLocation = "http://design.rryjw.com/showroom/upload/"+file.name;
				
				model.pictureArray.addItem(picture);
				model.pictureNum++;
				view.startUploadBtn.enabled = true;
				eventMap.mapListener(view.startUploadBtn, MouseEvent.CLICK, startUploadBtnClickHandler);
				
				var bitmap:Bitmap = Bitmap(loader.content);
				
				var bitmapdata:BitmapData = Matting.mattingStart(bitmap);
				model.prePic = bitmapdata;
				var encoder:mx.graphics.codec.PNGEncoder = new mx.graphics.codec.PNGEncoder();
				var byte:ByteArray = encoder.encode(bitmapdata);
				var Base64:Base64Encoder = new Base64Encoder();
				Base64.encodeBytes(byte);
				var image:String = Base64.toString();
				imgList.push(image);
			}
		}
		
		//开始上传
		public function startUploadBtnClickHandler(event:MouseEvent):void 
		{	
			/*var encode:mx.graphics.codec.PNGEncoder= new mx.graphics.codec.PNGEncoder();
			var byte:ByteArray = encode.encode(model.prePic);
			
			nc = new NetConnection();
			var rp:Responder = new Responder(successResult, errStatus);
			nc.client = nc;
			
			nc.objectEncoding = flash.net.ObjectEncoding.AMF3;
			//nc.connect("http://10.60.0.118/housediy/Gateway.aspx");
			nc.connect("http://design.rryjw.com/Gateway.aspx");
			var date:Date = new Date();
			var fileName:String =  date.fullYear.toString() + date.month.toString() + 
				date.date.toString() + date.hours.toString() + date.minutes.toString() + date.seconds.toString();
			nc.call("HouseDiyService.HouseDiyAction.savePic",rp, byte, fileName);*/
			var len:int = model.pictureArray.length;//len表示待上传的图片数目
			var urlArray:Array = new Array();//存储预上传的图片url

		 for (var i:int = 0; i < len; i++)
			{
				if (model.pictureArray[i].pictureUpdate == false)
				{		
					//readyArray[i].upload(uploadURL);
					model.pictureArray[i].pictureUpdate = true;
					urlArray.push(model.pictureArray[i].pictureLocation);
					model.pictureNum--;
					model.pictureArray.refresh();
				}
			}
			dispatch(new AddUserProductEvent(AddUserProductEvent.ADD_USER_PRODUCT, userModel.userID, imgList));
			
			eventMap.unmapListener(view.startUploadBtn, MouseEvent.CLICK, startUploadBtnClickHandler);
		}
		

		//从左侧list中删除待上传的图片
		private function deletePicture(event:DeleteObjEvent):void
		{
			var location:Number = model.pictureArray.getItemIndex(event.obj);
			model.pictureArray.removeItemAt(location);
		}
		
		//清空所有待上传的图片
		private function clearListBtnClickHandler(event:MouseEvent):void
		{
			model.pictureArray.removeAll();
			model.pictureNum = 0;		
		}
	}
}